<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Database connection and data parsing
 *
 * @author QuangKhoi
 */
class Database {

    private static $instance = null;

    /**
     * Return instance of the current database connection
     * @return instance
     */
    public static function getInstance() {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * constructor
     */
    public function __construct() {
        $this->dbConnect();
    }

    /**
     * Excute query
     * @param string $query
     */
    public function query($query) {
        if ($query != "") {
            $result = new QueryResult();
            mysql_set_charset('utf8');
            $result->dbReturn = mysql_query($query);
            if ($result->dbReturn != null)
                $result->returnCode = 200; //OK code
            else {
                $result->returnCode = 404; //Not found code
                $result->returnMessage = "Not found";
            }
            return $result;
        }
    }

    /**
     * Get total rows of the table
     * @param type $table
     */
    public function totalRows($table) {
        $query = "SELECT COUNT(*) AS num_rows FROM $table";
        $result = new QueryResult();
        mysql_set_charset('utf8');
        $result->dbReturn = mysql_query($query);
        if ($result->dbReturn != null) {
            $result->returnCode = 200; //OK code
            $row = mysql_fetch_object($result->dbReturn);
            $result->numRows = $row->num_rows;
        } else {
            $result->returnCode = 404; //Not found code
            $result->returnMessage = "Not found";
        }
        return $result;
    }
    
    /**
     * Get total rows of the table
     * @param type $table
     */
    public static function totalRowsWithWhere($table, $whereQuery) {
        $query = "SELECT COUNT(*) AS num_rows FROM $table WHERE $whereQuery";
        $result = new QueryResult();
        mysql_set_charset('utf8');
        $result->dbReturn = mysql_query($query);
        if ($result->dbReturn != null) {
            $result->returnCode = 200; //OK code
            $row = mysql_fetch_object($result->dbReturn);
            $result->numRows = $row->num_rows;
        } else {
            $result->returnCode = 404; //Not found code
            $result->returnMessage = "Not found";
        }
        return $result;
    }

    /**
     * Open connection to mysql server
     */
    public function dbConnect() {
        $hostname = Configuration::$hostname;
        $username = Configuration::$username;
        $password = Configuration::$password;
        $database = Configuration::$database;
        //Connect to db
        mysql_connect($hostname, $username, $password) or
                die("There's some mistakes in configuration. Please check it...");
        //Select database
        mysql_select_db($database);
        mysql_set_charset('utf8');
    }

    /**
     * Check dupplicate data
     * @param string $table
     * @param string $column
     * @param string $value
     * @return boolean
     */
    public static function isDupplicate($table, $column, $value) {
        $result = null;
        try {
            //Check the duplicate value (OK)
            $db = $this->getInstance();
            $result = $db->Query("SELECT * FROM $table WHERE $column = '$value'");
            $result->ReturnCode = 200;
            if ($result->dataTable->numOfRow > 0)
                return true;
        } catch (Exception $err) {
            //There's some mistakes with the user input value or database
            $result->returnCode = 409;
            $result->returnMessage = $err->getMessage();
        }
        return false;
    }

    /**
     * 
     * @param string $table
     * @param string $column
     * @return null
     */
    public static function getID($table, $column) {
        $result = null;
        try {
            //Check the duplicate value (OK)
            $db = self::getInstance();
            $result = $db->query("SELECT Max($column) FROM $table");
            if ($result->returnCode == 200) {
                if ($result->dataTable->numOfRow > 0 && $result->dataTable->rows[0] != "") {
                    $number = $result->dataTable->rows[0][0];
                    return self::formatID($column, $number + 1);
                } else
                    return self::formatID($column, 0);
            } else
                return null;
        } catch (Exception $err) {
            //There's some mistakes with the user input value or database
            $result->returnCode = 409;
            $result->returnMessage = $err->getMessage();
            $controller = new ErrorController(new Error(), new ErrorView(), $result->returnCode, $result->returnMessage);
            $controller->returnError();
        }
        return null;
    }

    /**
     * Return formated id base on column name
     * @param string $column
     * @param integer $value
     * @return formated id
     */
    public static function formatID($column, $value) {
        return str_pad($value, 0, "0", STR_PAD_LEFT);
    }

}

?>
